AddCSLuaFile("shared.lua")
include("shared.lua")

function ENT:Initialize()
Damage = 29  -- The Damage of the bullet.
PenDistance = 7 -- Penetration distance aka how far the bullet will penetrate when it hits something.
Speed = 915 -- Speed of the Bullet in m/s . Look in wikipedia for more info.
Force = 1340 -- Force of the Bullet in Joules (J) . Look in wikipedia for more info.

--General Init
self.Trace = self.Entity:GetVar("Trace",false)
self.LastThink = CurTime()
self.Trace.endpos = self.Dir

--Bullet Initialization
self.Bullet = {}
self.Bullet.Force = Force/103.48 --Source applied force to Joules conversion
self.Bullet.Damage = Damage
self.Bullet.Spread = Vector(0,0,0)
self.Bullet.Num = 1
self.Bullet.Tracer = 0
self.Bullet.Callback = function ( a, b, c ) BulletPenetration( 0, a, b, c ) end -- Penetration Callback

self.Entity:Fire("kill","",7) -- Kill this entity after awhile
self.Dir = self.Entity:GetForward()*(Speed*37.39*FrameTime()) -- Conversion : Inches to Meters multiplied by server tick
self:Think()
end

function ENT:Think() -- Do prediction serverside

trail = ents.Create("env_spritetrail")
trail:SetKeyValue("spritename","trails/smoke.vmt")
trail:SetKeyValue("lifetime","0.15")
trail:SetKeyValue("startwidth","3")
trail:SetKeyValue("endwidth","0")
trail:SetKeyValue("rendercolor","250 250 250")
trail:SetPos(self.Entity:GetPos())
trail:SetParent(self.Entity)
trail:Spawn()
trail:Activate()

sprite = ents.Create("env_sprite")
sprite:SetKeyValue("model","orangecore2.vmt")
sprite:SetKeyValue("rendercolor","255 165 0")
sprite:SetKeyValue("scale","0.05")
sprite:SetPos(self.Entity:GetPos())
sprite:SetParent(self.Entity)
sprite:Spawn()
sprite:Activate()

self.Trace.start = self.Entity:GetPos()
self.Trace.endpos = self.Entity:GetPos()+self.Dir
	
local TraceRes = util.TraceLine(self.Trace)
	if TraceRes.Hit then
	self.Bullet.Src = self.Trace.start
	self.Bullet.Dir = (TraceRes.HitPos - self.Trace.start)
	self.Owner:FireBullets(self.Bullet)

	self:Remove()
	elseif !TraceRes.Hit then
	self.Entity:SetPos(self.Entity:GetPos() + self.Dir)
	end
	self.Entity:NextThink(CurTime()) -- Update The position Every Server Tick.
	return true
end

function BulletPenetration( hitNum, attacker, tr, dmginfo ) --Bullet penetration code made by garry not by me !!

 	if ( CLIENT ) then return end 
 	if ( hitNum == 1 ) then return end 

 	local bullet = {} 	 
 		bullet.Num 		= 1 
 		bullet.Src 		= tr.HitPos + attacker:GetAimVector() * (PenDistance + 4)
 		bullet.Dir 		= attacker:GetAimVector() * PenDistance
 		bullet.Spread 	= Vector( 0.005, 0.005, 0 )
 		bullet.Force		= 20
		bullet.Tracer = 0
 		bullet.Damage	= Damage
 		bullet.AmmoType 	= "Pistol"  
 	if (SERVER) then 
 		bullet.Callback    = function( a, b, c ) BulletPenetration( hitNum + 1, a, b, c ) end 
 	end 
 	timer.Simple( 0.01, attacker.FireBullets, attacker, bullet ) 
end